<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-date-picker v-model="listQuery.startTime" type="datetime" placeholder="选择起始时间" style="width: 200px;"/>
      <el-date-picker v-model="listQuery.endTime" type="datetime" placeholder="选择结束时间" style="width: 200px;"/>
      <el-select v-model="listQuery.brandId" size="mini" style="width: 200px" class="filter-item" clearable placeholder="请选择商户">
        <el-option
          v-for="item in brandIdArray"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
        <!--<el-option v-for="(key, value) in settlementFlagMap" :key="key" :label="key" :value="value"/>-->
      </el-select>
      <el-button v-permission="['GET /admin/order/verifyCount']" size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button :loading="downloadLoading" size="mini" class="filter-item" type="warning" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" min-width="100" type="selection" sortable/>
      <el-table-column align="center" min-width="100" label="商户ID" prop="brandId"/>
      <el-table-column align="center" min-width="100" label="商户名" prop="brandName" sortable/>
      <el-table-column align="center" min-width="80px" label="支付总额" prop="actualPrice"/>
      <el-table-column align="center" min-width="90px" label="总佣金" prop="settlementMoney"/>
      <el-table-column align="center" min-width="120px" label="已结算金额" prop="alreadySettlement"/>
      <el-table-column align="center" min-width="120px" label="待结算金额" prop="waitSettlement"/>
      <el-table-column align="center" min-width="120px" label="未结算金额" prop="noSettlement"/>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<style>
.box-card {
  margin: 30px 0px;
}
.box-card .el-form-item {
  margin-bottom: 5px;
}
</style>

<script>
import { verifyBrandList,verifyCount } from '@/api/business/order'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import checkPermission from '@/utils/permission' // 权限判断函数

export default {
  name: 'VerifyOrder',
  components: { Pagination },
  data() {
    return {
      list: undefined,
      total: 0,
      listLoading: true,
      shipChannelList: [],
      listQuery: {
        page: 1,
        limit: 20,
        brandId: undefined,
        startTime: undefined,
        endTime: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      brandIdArray: [],
      refundDialogVisible: false,
      downloadLoading: false
    }
  },
  created() {
    this.getVerifyBrandList()
    this.getList()
  },
  methods: {
    checkPermission,
    selectionRowsChange(val){
      let sum = 0
      val.forEach(item =>{
        sum += item.actualPrice
      })
      this.listQuery.sumAmount = parseFloat(sum).toFixed(2)
      this.rows = val
    },
    getList() {
      this.listLoading = true
      verifyCount(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    getVerifyBrandList() {
      verifyBrandList().then(response => {
        this.brandIdArray = response.data.data.brandList
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.page = 1
      this.getList()
    },
    commonBatchVerity(data) {
      var orderIdList = '';
      data.forEach(item =>{
        orderIdList = orderIdList + item.id + ','
      })
      if (orderIdList.length > 0) {
        this.$confirm('您确定要结算吗？').then(() => {
          finishOrder(orderIdList).then(response => {
            console.info(response)
            this.$notify.success({
              title: '成功',
              message: '操作成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }).catch(() => {
          console.log('cancel')
        })
      }
    },
    handleBatchVerity() {
      this.commonBatchVerity(this.rows)
    },
    handleSettlement(id) {
      var data = [{'id': id}]
      this.commonBatchVerity(data)
    },
    handleDetail(row) {
      verifyDetail(row.id).then(response => {
        this.orderDetail = response.data.data
      })
      this.orderDialogVisible = true
    },

    handleShip(row) {
      this.shipForm.orderId = row.id
      this.shipForm.shipChannel = row.shipChannel
      this.shipForm.shipSn = row.shipSn

      this.shipDialogVisible = true
      this.$nextTick(() => {
        this.$refs['shipForm'].clearValidate()
      })
    },
    confirmShip() {
      this.$refs['shipForm'].validate((valid) => {
        if (valid) {
          verifyList(this.shipForm).then(response => {
            this.shipDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '确认发货成功'
            })
            this.getList()
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    printOrder(orderDetail) {
      // 获取要打印的Dom内容
      let printHtml = '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"/><title>小票打印</title><style type="text/css">        *{padding:0;margin: 0;}        h1{font-size: 20px;}        h3{font-size: 16px;}        .left{            float: left;        }        .right{            float:right;        }        .clearfix{            clear: both;        }        ul{list-style: none;}        .print_container{            padding: 10px;            width: 300px;        }        .section1{        }        .section2 label{            display: block;        }        .section3 label{            display: block;        }        .section4{        }        .section4 .total label{            display: block;        }        .section4 .other_fee{            border-bottom: 1px solid #DADADA;        }        .section5 label{            display: block;        }</style></head><body style="background-color:#fff;"><div class="print_container"><h1>销售发货单</h1><span>*****************************************</span><div class="section2"><label>订单编号：{{orderSn}}</label><label>下单时间：{{payTime}}</label><label>配送方式：{{freightType}}</label></div><span>*****************************************</span><div class="section4"><div style="border-bottom: 1px solid #DADADA;"><table style="width: 100%;"><thead><tr><td width="70%">商品名称</td><td width="13%" style="text-align:center;">数量</td><td width="17%" style="text-align:right;">金额</td></tr></thead><tbody>{{goodsHtml}}</tbody></table></div><div class="other_fee"><div class="canh"><label class="left">商品总价</label><label class="right">{{goodsPrice}}</label><div class="clearfix"></div></div><div class="peis"><label class="left">配送费</label><label class="right">{{freightPrice}}</label><div class="clearfix"></div></div><div class="manj"><label class="left">立减优惠</label><label class="right">{{couponPrice}}</label><div class="clearfix"></div></div></div><div class="total"><label class="left">总计</label><label class="right">{{actualPrice}}</label><div class="clearfix"></div></div>{{payHtml}}<span>*****************************************</span></div><div class="section3"><div class="total"><label class="left">收货人：</label><label class="right">{{consignee}}</label><div class="clearfix"></div></div><div class="total"><label class="left">电话：</label><label class="right">{{mobile}}</label><div class="clearfix"></div></div><label>{{address}}</label></div><span>*****************************************</span><div class="section2"><label>【用户留言】<span style="font-size: 16px;">{{message}}</span></label></div></div></body></html>'
      const orderSn = orderDetail.order.orderSn
      printHtml = printHtml.replace('{{orderSn}}', orderSn)
      const payTime = orderDetail.order.payTime == null ? '' : orderDetail.order.payTime
      printHtml = printHtml.replace('{{payTime}}', payTime)
      const freightType = orderDetail.order.freightType === 1 ? '自提' : '快递'
      printHtml = printHtml.replace('{{freightType}}', freightType)
      let goodsHtml = ''
      for (var i = 0; i < orderDetail.orderGoods.length; i++) {
        const preS = orderDetail.orderGoods[i].refundId != null ? '<s>' : ''
        const endS = orderDetail.orderGoods[i].refundId != null ? '【已退货】</s>' : ''
        goodsHtml = goodsHtml + '<tr><td style="font-size: 14px;">' + preS + orderDetail.orderGoods[i].goodsName
        goodsHtml = goodsHtml + '【' + orderDetail.orderGoods[i].specifications + '】' + endS
        goodsHtml = goodsHtml + '</td><td style="text-align:center;">' + orderDetail.orderGoods[i].number + '</td><td style="text-align:right;">' + orderDetail.orderGoods[i].price + '</td></tr>'
      }
      printHtml = printHtml.replace('{{goodsHtml}}', goodsHtml)
      const goodsPrice = orderDetail.order.goodsPrice
      printHtml = printHtml.replace('{{goodsPrice}}', goodsPrice)
      const freightPrice = orderDetail.order.freightPrice
      printHtml = printHtml.replace('{{freightPrice}}', freightPrice)
      const couponPrice = orderDetail.order.couponPrice
      printHtml = printHtml.replace('{{couponPrice}}', couponPrice)
      const actualPrice = orderDetail.order.actualPrice
      printHtml = printHtml.replace('{{actualPrice}}', actualPrice)
      const payHtml = orderDetail.order.payTime == null ? '' : '<div style="text-align: right;"><label>顾客已付款</label></div>'
      printHtml = printHtml.replace('{{payHtml}}', payHtml)
      const consignee = orderDetail.order.consignee
      printHtml = printHtml.replace('{{consignee}}', consignee)
      const mobile = orderDetail.order.mobile
      printHtml = printHtml.replace('{{mobile}}', mobile)
      const address = orderDetail.order.address
      printHtml = printHtml.replace('{{address}}', address)
      const message = orderDetail.order.message
      printHtml = printHtml.replace('{{message}}', message)
      var printWin = window.open('', 'printWin', 'height=800, width=1000, top=50, left=50, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
      // const newDomHtml = window.document.getElementById('pdfDom').innerHTML
      printWin.window.document.body.innerHTML = printHtml
      printWin.print()
      return false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['商户ID', '商户名', '支付总额', '总佣金', '已结算金额', '待结算金额', '未结算金额']
        const filterVal = ['brandId', 'brandName', 'actualPrice', 'settlementMoney', 'alreadySettlement', 'waitSettlement', 'noSettlement']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '结算统计')
        this.downloadLoading = false
      })
    }
  }
}
</script>
